import React, { useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { selectTextById, updateTextProperties } from '@/store/textsSlice'; // Changed selector
import type { RootState } from '@/store';
import type { Text } from '@/store/textTypes';
import { Form, InputNumber, Switch, Typography, Row, Col, Slider, Button } from 'antd'; // Added Slider
import { createGlobalStyle } from 'styled-components';

const { Title, Text } = Typography;

// 全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* ... (样式代码与之前组件相同，此处为简洁省略) ... */
    .config-text-clip-scroll::-webkit-scrollbar { width: 3px; background: transparent; }
    .config-text-clip-scroll::-webkit-scrollbar-thumb { background: #715BB8; border-radius: 4px; }
    .ant-form-item-label > label { color: #FFFFFF !important; }
    .ant-input, .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important; color: #FFFFFF !important; border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus, .ant-input-number:hover, .ant-input-number:focus {
        border-color: #888888 !important; box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-input-number-handler-wrap { background-color: #3C3C3C !important; }
    .ant-input-number-handler { color: #FFFFFF !important; border-color: #555555 !important; }
    .ant-slider-rail { background-color: #555555 !important; }
    .ant-slider-track { background-color: #FFFFFF !important; }
    .ant-slider-handle { border: solid 2px #FFFFFF !important; background-color: #3C3C3C !important; }
    .ant-switch { background-color: #555555 !important; }
    .ant-switch-checked { background-color: #715BB8 !important; }
`;

interface ConfigTextClipFormProps {
    textId: string;
}

// 辅助组件：用于创建标签-滑块-数值输入的组合行
const SliderInputRow: React.FC<{
    label: string;
    name: string[];
    sliderProps: any;
    inputProps: any;
}> = ({ label, name, sliderProps, inputProps }) => (
    <Form.Item>
        <Row align="middle" gutter={16}>
            <Col span={6}>
                <Text style={{ color: '#FFFFFF' }}>{label}</Text>
            </Col>
            <Col span={12}>
                <Form.Item name={name} noStyle>
                    <Slider {...sliderProps} />
                </Form.Item>
            </Col>
            <Col span={6}>
                <Form.Item name={name} noStyle>
                    <InputNumber style={{ width: '90%' }} {...inputProps} />
                </Form.Item>
            </Col>
        </Row>
    </Form.Item>
);

const ConfigTextClipForm: React.FC<ConfigTextClipFormProps> = ({ textId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    // **改动: 使用 selectTextById 获取整个文本对象，因为 clip_settings 是其一部分**
    const text = useSelector((state: RootState) => (textId ? selectTextById(state, textId) : null));

    const handleValuesChange = useCallback(
        (changedValues: any, allValues: any) => {
            if (textId) {
                dispatch(
                    updateTextProperties({
                        id: textId,
                        updates: { clip_settings: allValues.clip_settings },
                    })
                );
            }
        },
        [textId, dispatch]
    );

    useEffect(() => {
        if (text?.clip_settings) {
            form.setFieldsValue({ clip_settings: text.clip_settings });
        } else {
            form.resetFields();
        }
    }, [text, form]);

    if (!textId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何文本片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            <div
                className="config-text-clip-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前选择
                </Title>
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '24px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>
                        <i className="icon-text">T</i> {text?.content.substring(0, 20) || '未命名文本'}...
                    </Text>
                </div>

                <Title level={5} style={{ color: '#FFFFFF', marginTop: 0 }}>
                    剪辑设置
                </Title>
                <Form form={form} layout="vertical" onValuesChange={handleValuesChange}>
                    {/* **改动: 使用 SliderInputRow 优化布局** */}
                    <SliderInputRow label="透明度" name={['clip_settings', 'alpha']} sliderProps={{ min: 0, max: 1, step: 0.01 }} inputProps={{ min: 0, max: 1, step: 0.01 }} />
                    <SliderInputRow
                        label="旋转"
                        name={['clip_settings', 'rotation']}
                        sliderProps={{ min: 0, max: 360, step: 1 }}
                        inputProps={{
                            min: 0,
                            max: 360,
                            step: 1,
                            addonAfter: '°',
                        }}
                    />
                    <SliderInputRow label="水平缩放" name={['clip_settings', 'scale_x']} sliderProps={{ min: 0.1, max: 1, step: 0.1 }} inputProps={{ min: 0.1, max: 1, step: 0.1 }} />
                    <SliderInputRow label="垂直缩放" name={['clip_settings', 'scale_y']} sliderProps={{ min: 0.1, max: 1, step: 0.1 }} inputProps={{ min: 0.1, max: 1, step: 0.1 }} />
                    <SliderInputRow label="水平偏移" name={['clip_settings', 'transform_x']} sliderProps={{ min: -1, max: 1, step: 0.1 }} inputProps={{ min: -1, max: 1, step: 0.1 }} />
                    <SliderInputRow label="垂直偏移" name={['clip_settings', 'transform_y']} sliderProps={{ min: -1, max: 1, step: 0.1 }} inputProps={{ min: -1, max: 1, step: 0.1 }} />
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="水平翻转" name={['clip_settings', 'flip_horizontal']} valuePropName="checked">
                                <Switch />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="垂直翻转" name={['clip_settings', 'flip_vertical']} valuePropName="checked">
                                <Switch />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
        </>
    );
};

export default ConfigTextClipForm;
